package edu.gyu.myshop.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import edu.gyu.myshop.model.*;
import edu.gyu.myshop.dao.UserAddressDao;
import edu.gyu.myshop.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import edu.gyu.myshop.model.Myuser;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author ls
 * @since 2024-06-18
 */
@Service
public class UserAddressServiceImpl extends ServiceImpl<UserAddressDao, UserAddress> implements UserAddressService {
    @Autowired
    MyuserService myuserService;

    @Autowired
    MyorderService myorderService;
    @Autowired
    OrderDetailService orderDetailService;

    @Autowired
    UserAddressService userAddressService;
    @Autowired
    GoodsService goodsService;
    // 初始化密码编码器
    BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();

    @Override
    public boolean adminLogin(Myuser myuser, HttpServletRequest request) {
        Myuser user = myuserService.lambdaQuery()
                .eq(Myuser::getUsername, myuser.getUsername())
                .one();

        if (user != null && user.getType() == 1) {
            if (passwordEncoder.matches(myuser.getPassword(), user.getPassword())) {
                // 如果用户存在且密码匹配，则将密码清空并存入session
                user.setPassword("");
                request.getSession().setAttribute("user", user);
                return true;
            }
            String msg = "用户名或密码错误";
            request.setAttribute("msg", msg);
            return false;
        }
        String msg = "不是管理员";
        request.setAttribute("msg", msg);
        return false;
    }

    @Override
    public int getUserAll() {
        return myuserService.list().size();
    }

    @Override
    public String getLoginUser(HttpServletRequest request) {
        // 从Session中获取用户名
        Myuser user = (Myuser) request.getSession().getAttribute("user");
        request.setAttribute("username", user.getUsername());
        return user.getUsername();
    }

    @Override
    public int getTodayRegisterUser() {
        // 获取今天的日期时间范围
        LocalDateTime startOfToday = LocalDateTime.of(LocalDate.now(), LocalTime.MIN);
        LocalDateTime endOfToday = LocalDateTime.of(LocalDate.now(), LocalTime.MAX);
        // 调用 MyUserService 中的方法，查询今天注册的用户
        List<Myuser> todayRegisteredUsers = myuserService.lambdaQuery()
                .ge(Myuser::getCreateTime, startOfToday)
                .le(Myuser::getCreateTime, endOfToday)
                .list();
        return todayRegisteredUsers.size();
    }

    @Override
    public int getTodayOrder() {
        // 获取今天的日期时间范围
        LocalDateTime startOfToday = LocalDateTime.of(LocalDate.now(), LocalTime.MIN);
        LocalDateTime endOfToday = LocalDateTime.of(LocalDate.now(), LocalTime.MAX);
        return orderDetailService.lambdaQuery()
                .ge(OrderDetail::getCreateTime, startOfToday)
                .le(OrderDetail::getCreateTime, endOfToday)
                .list().size();
    }

    @Override
    public int getOrderAll() {
        return orderDetailService.list().size();
    }

    @Override
    public IPage<OrderDetail> listOrder(int page, int size) {
        return orderDetailService.getOrderDetailsWithStatusOne(page, size);
    }

    @Override
    public IPage<OrderDetail> listOrderAll(int page, int size) {
        Page<OrderDetail> pageRequest = new Page<>(page, size);
        // 使用 QueryWrapper 指定排序条件
        QueryWrapper<OrderDetail> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("id"); // 按 id 倒序排序
        IPage<OrderDetail> orderDetailPage = orderDetailService.page(pageRequest, queryWrapper);
        List<OrderDetail> list = orderDetailPage.getRecords();
        list.forEach(orderDetail -> {
            orderDetail.setProductName(goodsService.getById(orderDetail.getGoodsid()).getName());
            Myorder myorder = myorderService.getById(orderDetail.getOrderid());
            if (myorder != null) {
                orderDetail.setStatus(String.valueOf(myorder.getStatus())); // 获取订单状态
            }
        });
        return orderDetailPage;
    }

    @Override
    public IPage<OrderDetail> listOrderAll_Delivery(int page, int size) {
        // 创建分页请求对象
        Page<OrderDetail> pageRequest = new Page<>(page, size);
        ArrayList<OrderDetail> orderDetails = new ArrayList<>();
        List<OrderDetail> list = orderDetailService.list();
        // 遍历每个 OrderDetail 实例
        list.forEach(orderDetail -> {
            // 查询符合条件的 Myorder 实例
            List<Myorder> myorders = myorderService.lambdaQuery()
                    .eq(Myorder::getId, orderDetail.getOrderid())
                    .eq(Myorder::getStatus, "1")
                    .list();
            if (!myorders.isEmpty()) {
                orderDetail.setStatus("1");
                orderDetails.add(orderDetail);
            }
            orderDetail.setProductName(goodsService.getById(orderDetail.getGoodsid()).getName());
        });
        Page<OrderDetail> orderDetailPage = pageRequest.setRecords(orderDetails);
        // 返回分页后的 OrderDetail 对象
        return orderDetailPage;
    }

    @Override
    public IPage<OrderDetail> listOrderAll_Receive(int page, int size) {
        // 创建分页请求对象
        Page<OrderDetail> pageRequest = new Page<>(page, size);
        ArrayList<OrderDetail> orderDetails = new ArrayList<>();
        List<OrderDetail> list = orderDetailService.list();
        // 遍历每个 OrderDetail 实例
        list.forEach(orderDetail -> {
            // 查询符合条件的 Myorder 实例
            List<Myorder> myorders = myorderService.lambdaQuery()
                    .eq(Myorder::getId, orderDetail.getOrderid())
                    .eq(Myorder::getStatus, "2")
                    .list();
            if (!myorders.isEmpty()) {
                orderDetail.setStatus("2");
                orderDetails.add(orderDetail);
            }
            orderDetail.setProductName(goodsService.getById(orderDetail.getGoodsid()).getName());
        });
        Page<OrderDetail> orderDetailPage = pageRequest.setRecords(orderDetails);
        // 返回分页后的 OrderDetail 对象
        return orderDetailPage;
    }

    @Override
    public IPage<OrderDetail> listOrderAll_Complete(int page, int size) {
        // 创建分页请求对象
        Page<OrderDetail> pageRequest = new Page<>(page, size);
        ArrayList<OrderDetail> orderDetails = new ArrayList<>();
        List<OrderDetail> list = orderDetailService.list();
        // 遍历每个 OrderDetail 实例
        list.forEach(orderDetail -> {
            // 查询符合条件的 Myorder 实例
            List<Myorder> myorders = myorderService.lambdaQuery()
                    .eq(Myorder::getId, orderDetail.getOrderid())
                    .eq(Myorder::getStatus, "3")
                    .list();
            if (!myorders.isEmpty()) {
                orderDetail.setStatus("3");
                orderDetails.add(orderDetail);
            }
            orderDetail.setProductName(goodsService.getById(orderDetail.getGoodsid()).getName());
        });
        Page<OrderDetail> orderDetailPage = pageRequest.setRecords(orderDetails);
        // 返回分页后的 OrderDetail 对象
        return orderDetailPage;
    }

    @Override
    public IPage<Myuser> listUser(int page, int size) {
        return myuserService.userPage(page, size);
    }

    @Override
    public boolean postAddUser(Myuser myuser, HttpServletRequest request) {
        Myuser user = myuserService.lambdaQuery()
                .eq(Myuser::getUsername, myuser.getUsername())
                .one();
        if (user != null) {
            String msg = "用户名被占用！";
            request.setAttribute("msg2", msg);
            return false;
        } else {
            // 对密码进行加密
            BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
            String encodedPassword = passwordEncoder.encode(myuser.getPassword());
            myuser.setPassword(encodedPassword);
            // 设置创建时间
            myuser.setCreateTime(LocalDateTime.now());
            myuserService.save(myuser);
            String msg = myuser.getUsername() + "添加成功";
            request.setAttribute("msg2", msg);
            return true;
        }
    }

    @Override
    public boolean userUpdate(Myuser myuser, HttpServletRequest request) {
        // 获取现有用户
        Myuser existingUser = myuserService.getById(myuser.getId());
        if (existingUser != null) {
            // 检查用户名是否已被其他用户占用
            LambdaQueryWrapper<Myuser> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Myuser::getUsername, myuser.getUsername());
            Myuser userWithSameUsername = myuserService.getOne(queryWrapper);
            if (userWithSameUsername != null && userWithSameUsername.getId() != myuser.getId()) {
                request.setAttribute("msg2", "用户名已被占用");
                return false;
            }
            existingUser.setUsername(myuser.getUsername());
            if (!myuser.getPassword().isEmpty()) {
                BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
                String encodedPassword = passwordEncoder.encode(myuser.getPassword());
                existingUser.setPassword(encodedPassword);
            }
            existingUser.setType(myuser.getType());
            existingUser.setCreateTime(LocalDateTime.now());
            myuserService.save(existingUser);
            return true;
        } else {
            request.setAttribute("msg2", "用户不存在");
            return false;
        }
    }

    @Override
    public OrderDetail getOrderDetail(int id) {
        //返回订单列表
        OrderDetail orderDetail = orderDetailService.getById(id);
        orderDetail.setProductName(goodsService.getById(orderDetail.getGoodsid()).getName());
        userAddressService.list().forEach(userAddress -> {
                    if (userAddress.getUserId() == orderDetail.getUserid()) {
                        orderDetail.setAddress(userAddress.getAddress());
                        orderDetail.setPhone(userAddress.getPhone());
                        orderDetail.setUsername(userAddress.getName());
                    }
                }
        );
        orderDetail.setStatus(String.valueOf(myorderService.getById(orderDetail.getOrderid()).getStatus()));
        orderDetail.setPicture(goodsService.getById(orderDetail.getGoodsid()).getPicture());
        return orderDetail;
    }

    @Override
    public boolean updatePassword(HttpSession session, String oldPassword, String newPassword) {
        // 从Session中获取用户名
        Myuser userSession = (Myuser) session.getAttribute("user");
        Myuser user = myuserService.lambdaQuery()
                .eq(Myuser::getUsername, userSession.getUsername())
                .one();
        if (user != null && user.getType() == 1) {
            if (passwordEncoder.matches(oldPassword, user.getPassword())) {
                user.setPassword(passwordEncoder.encode(newPassword));
                myuserService.updateById(user);
                return true;
            }
        }
        return false;
    }


}
